//
//  WeiboAPIManager.swift
//  weibo
//
//  Created by yellow on 15/10/16.
//  Copyright © 2015年 yellow. All rights reserved.
//

import UIKit


/// 新浪微博api操作的封装
class WeiboAPIManager: NSObject {
    
    private let appKey = "4034202280"
    private let appSecret = "86bb9aab02e28f704cd0ee5a06895ff1"
    private let redirectURL = "http://www.baidu.com"
    

    static let manager = WeiboAPIManager()
    override init() {
        self.networkingManager = NetworkingTools.manager
    }
    private var networkingManager:NetworkingProtocol
    
    
}

// MARK: - 私有方法
private extension WeiboAPIManager{

    /// 将weibo请求所必须得token封装在内部，当token无效时会返回闭包提示错误。使用者将不再关心token，该方法会将token以参数的形式追加到parameter中.
    ///
    /// - parameter httpMethod: http请求方式：post或者是get
    /// - parameter URLString:  请求url的string
    /// - parameter parameter:  参数字典
    /// - parameter finished:   执行完成后的闭包
    func requestWithToken(httpMethod:HttpMethod,URLString:String,var parameter:[String: AnyObject]?,finished:FinishedBlock){
        guard let token = userToken else{
            //如果有token(有效)
            finished!(result:nil, error:NSError(domain: "cn.itcast.error", code: -110, userInfo: ["message" : "token为nil"]))
            return
        }
        
        // 2. 判断参数字典,为nil就创建一个新的字典
        if parameter == nil {
            parameter = [String: AnyObject]()
        }
        parameter!["access_token"] = token
        
        self.networkingManager.httpRequest(httpMethod, URLString: URLString, parameter: parameter, finished: finished)
    }
    
    //上传文件(如：图片)
    func loadData(weiboText:String,data:NSData,finished:FinishedBlock){
        let URL = "https://upload.api.weibo.com/2/statuses/upload.json"
        guard let token = userToken else{
            //如果有token(有效)
            finished!(result:nil, error:NSError(domain: "cn.itcast.error", code: -110, userInfo: ["message" : "token为nil"]))
            return
        }
        
        //构建上传图片并发布一条新微博所需的参数
        var parameter = [String: AnyObject]()
        parameter["access_token"] = token
        parameter["status"] = weiboText
        
        //发起网络请求
        self.networkingManager.httpUpload(data, name: "pic", URLString: URL, parameter: parameter, finished: finished)
    }
}

// MARK: - 计算型属性
extension WeiboAPIManager{
    
    //如果有返回token，否则返回nil
    var userToken:String?{
        if let token = UserAccountViewModel.sharedViewModel.userToken {
            return token
        }else{
            return nil
        }
    }
}



// MARK: - 微博接口
extension WeiboAPIManager{
    
    /// 加载微博数据
    ///
    /// - parameter since_id:   若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    /// - parameter max_id:     若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    /// - parameter finished:   完成回调
    /// - see: [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)
    func getCurrentUserAllWeiboFromLast(since_id since_id: Int, max_id: Int,finishedBlock:FinishedBlock){
        let URL = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        var parmas:[String:AnyObject] = [String:AnyObject]()
        // 2. 上/下刷新参数
        if since_id > 0 {
            parmas["since_id"] = since_id
        } else if max_id > 0 {
            //-1是因为返回比最后一个微博，还要后面的微博
            parmas["max_id"] = max_id - 1
        }
        self.requestWithToken(HttpMethod.GET, URLString: URL, parameter: parmas, finished: finishedBlock)
    }
    
    /// 发布微博,传递图片后，就会执行发送图片微博的分支
    ///
    /// - parameter weiboText:     微博文本
    /// - parameter weiboPicture:  微博配图
    /// - parameter finishedBlock: 完成回调
    func composeWeibo(weiboText:String,weiboPicture:UIImage?,finishedBlock:FinishedBlock){
        
        //微博发图片
        if let image = weiboPicture {
            //将UIImage转换为二进制数据
            let imageData = UIImagePNGRepresentation(image)!
            loadData(weiboText, data: imageData, finished: finishedBlock)
        }else{
            //微博发送纯文本
            let URL = "https://api.weibo.com/2/statuses/update.json"
            
            let parmas:[String:AnyObject] = [
                "status":weiboText
            ]
            self.requestWithToken(HttpMethod.POST, URLString: URL, parameter: parmas, finished: finishedBlock)
        }
    }

}


// MARK: - 调用用户API的封装
extension WeiboAPIManager{
    
    //返回申请app授权的url
    var authorizeURL:NSURL{
        let URL = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectURL)"
        return NSURL(string: URL)!
    }
    
    //根据code拿回token
    func getUersToken(code:String,finishedBlock:FinishedBlock ){
        let params = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectURL]
        
        self.networkingManager.httpRequest(HttpMethod.POST, URLString: "https://api.weibo.com/oauth2/access_token", parameter: params, finished: finishedBlock)
    }
    
    //根据uid获取用户的基本信息
    func loadUserInfo(uid:String,finishedBlock:FinishedBlock){
        let URL = "https://api.weibo.com/2/users/show.json?"

        let parmas:[String:AnyObject] = [
            "uid":uid
        ]
        self.requestWithToken(HttpMethod.GET, URLString: URL, parameter: parmas, finished: finishedBlock)
    }
}
